<?php

namespace App\Console\Commands;

use App\Enum\OrderEnum;
use App\Models\AdminConfigModel;
use App\Models\OrderModel;
use Illuminate\Console\Command;
use Symfony\Component\Console\Output\ConsoleOutput;

class AssignOrderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'assignOrder {debug?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更改服务订单为指派订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(ConsoleOutput $output)
    {

        $debug = $this->argument('debug');
        $output->writeln('===========更改服务订单为指派订单开始===========');

        $config = AdminConfigModel::query()->find(1)->toArray();
        $appointOrderTime = $config['appoint_order_time'] ?? 0;
        $pendingOrder = OrderModel::query()->where('status', '=', OrderEnum::STATUS_PENDING_ORDER)->get();

        if($debug){
            $pendingOrder = OrderModel::query()->where('status', '=', OrderEnum::STATUS_PENDING_ORDER)->where('user_id',1)->get();
        }

        if($pendingOrder->isEmpty()){
            $output->writeln('没有待接单的订单');
        }
        else
        foreach ($pendingOrder->toArray() as $item){
            // 计算出发时间的 3 小时前的时间
            $threeHoursBefore = date('Y-m-d H:i:s', $item['start_time'] - $appointOrderTime * 3600);

            // 如果当前时间大于出发时间的 3 小时前的时间，就把订单状态改为指派订单
            if(time() > strtotime($threeHoursBefore)){
               if(empty($item['driver_id'])){
                   $order = OrderModel::query()->find($item['id']);
                   $order->status = OrderEnum::STATUS_TIMEOUT;
                   $order->order_type = OrderEnum::ORDER_TYPE_ASSIGN;
                   if(!$order->save()){
                       $output->writeln('订单号：'.$item['order_no'].'，状态：'.$item['status'].'，更改为指派订单失败');
                   }
               }
            }
        }
        $output->writeln('===========更改服务订单为指派订单结束===========');
        return 0;
    }
}
